package com.mini.common.thread;

import com.alibaba.csp.sentinel.util.StringUtil;
import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

import static com.mini.common.interceptor.AutoLogAspect.REQUEST_ID;


public class MdcRunable {

    public static void setRequestIdIfAbsent(String requestId) {
        if (StringUtil.isEmpty(requestId)) {
            MDC.put(REQUEST_ID, UUID.randomUUID().toString().replace("-", ""));
        } else {
            MDC.put(REQUEST_ID, requestId);
        }
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setRequestIdIfAbsent(MDC.get(REQUEST_ID));
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {

        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setRequestIdIfAbsent(MDC.get(REQUEST_ID));
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
